package personal.pheonix.focus.dan.client;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/10/14.
 */
public class BaseClient {
    private final static String HOST_URL="http://localhost:8080/billiards/";
    private  static String  postMothed(Map<String, String> params, String methodName) throws Exception
    {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(HOST_URL+methodName);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        String jsonBody;
        for (Map.Entry<String, String> entry : params.entrySet())
        {
            System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
            nvps.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
        }
        httpPost.setEntity(new UrlEncodedFormEntity(nvps));
        CloseableHttpResponse response2 = httpclient.execute(httpPost);
        try {
            HttpEntity entity2 = response2.getEntity();
            jsonBody= EntityUtils.toString(entity2);
            EntityUtils.consume(entity2);
        } finally {
            response2.close();
        }
        return  jsonBody;
    }
    protected String httpPost(Map<String, String> params) throws Exception {
        return postMothed(params, (new RuntimeException()).getStackTrace()[1].getMethodName());
    }
    public static void main(String[] args) throws Exception {

        Map<String, String> params=new HashMap<>();
        params.put("username","12");
        params.put("password","1");
        postMothed(params,"/checkUser");
    }
}
